package com.demo.tests.base;

import com.demo.config.ApiHeaders;
import com.demo.config.ConfigLoader;
import com.demo.config.DatabaseConfig;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;

public class BaseTest {
    protected static RequestSpecification requestSpec;

    @BeforeSuite
    public void globalSetup() {
        // 1. 初始化数据库连接池
        initializeDatabase();

        // 2. 配置HTTP客户端超时
        HttpClientConfig httpClientConfig = HttpClientConfig.httpClientConfig()
                .setParam("http.socket.timeout", 30000)
                .setParam("http.connection.timeout", 30000);

        RestAssuredConfig config = RestAssured.config()
                .httpClient(httpClientConfig);

        // 3. 构建RequestSpecification
        requestSpec = new RequestSpecBuilder()
                .setBaseUri(ConfigLoader.getProperty("api.base.url"))
                .setContentType("application/json")
                .addHeader("token", ApiHeaders.TOKEN)
                .addHeader("uid", "1")
                .setConfig(config)
                .build();

        // 4. 设置全局请求规范
        RestAssured.requestSpecification = requestSpec;
    }

    @AfterSuite
    public void globalTeardown() {
        // 关闭数据库连接池
        DatabaseConfig.close();
    }

    /**
     * 初始化数据库连接池
     */
    private void initializeDatabase() {
        try {
            // 从配置文件加载数据库配置
            String dbUrl = ConfigLoader.getProperty("db.url");
            String dbUsername = ConfigLoader.getProperty("db.username");
            String dbPassword = ConfigLoader.getProperty("db.password");
            String dbDriver = ConfigLoader.getProperty("db.driver");

            // 初始化数据库配置
            DatabaseConfig.init(dbUrl, dbUsername, dbPassword, dbDriver);

            // 验证数据库连接
            DatabaseConfig.testConnection();

        } catch (Exception e) {
            throw new RuntimeException("数据库初始化失败", e);
        }
    }
}